package com.imooc.api.intercepeter;

import com.imooc.api.exceptions.GraceException;
import com.imooc.api.util.IPUtil;
import com.imooc.constant.RedisKeyConstant;
import com.imooc.grace.result.ResponseStatusEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class SMSInterceptor implements HandlerInterceptor {


    private static  final Logger LOG = LoggerFactory.getLogger(SMSInterceptor.class);


    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String ip = IPUtil.getRequestIp(request);

        Boolean exist = stringRedisTemplate.hasKey(RedisKeyConstant.MOBILE_SMS_CODE + ip);
        if (Boolean.TRUE.equals(exist)){
            LOG.error("发送短信验证码太快了，请稍后再发");
            GraceException.display(ResponseStatusEnum.SMS_NEED_WAIT_ERROR);

        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
